<?php

namespace App\Services;

use App\Models\Openid;
use App\Models\User;
use App\Repository\UserRepo;
use Jiannei\Response\Laravel\Support\Facades\Response;
use Overtrue\LaravelWeChat\EasyWeChat;

class OpenLoginService
{
    public function getLoginUser($type, $data)
    {
        $allowType = ['phone', 'email', 'wx_mini'];
        if (!in_array($type, $allowType)) {
            Response::fail('请选择正确的方式登录！');
        }

        if (in_array($type, ['phone', 'email'])) {
            if (empty($data[$type])) {
                Response::fail('请输入正确的账号！');
            }
            $user = User::query()->where($type, $data[$type])->first();
            if (!password_verify($data['password'], $user->password)) {
                Response::fail('账号不存在或密码有误！');
                return false;
            }
        } else {
            $openUser = $this->getOpenLogin($type, $data);
            if ($openUser->user_id) {
                $user = User::query()->find($openUser->user_id);
                if (!$user) {
                    $user = UserRepo::create($openUser);
                    $openUser->user_id = $user->id;
                    $openUser->save();
                }
            } else {
                $user = UserRepo::create($openUser);
                $openUser->user_id = $user->id;
                $openUser->save();
            }
        }

        return $user;
    }

    public function getOpenLogin($type, $data)
    {
        $info = $this->parseInfo($type, $data);
        if (empty($info['openid'])) {
            Response::fail('未获取到OPENID！');
        }

        $openLogin = Openid::query()->firstOrCreate(['openid' => $info['openid']], $info);
        if (!$openLogin->user_id && $openLogin->unionid) {
            $same = Openid::where(['unionid' => $openLogin->unionid])->first();

            if ($same) {
                $openLogin->user_id = $same->user_id;
                $openLogin->save();
            }
        }

        return $openLogin;
    }

    public function parseInfo($type, $data)
    {
        if ($type == 'wx_mini') {
            $result = EasyWeChat::miniApp()->getUtils()->codeToSession($data['code']);

            return [
                'type' => $type,
                'openid' => $result['openid'],
                'unionid' => $result['unionId'] ?? null,
                'extra' => $result,
            ];
        } elseif ($type == 'password') {
            return [];
        }

        return [];
    }

}
